#pragma once

#include "log.hpp"
#include "Socket.hpp"
#include <signal.h>
#include <functional>

using func_t = std::function<std::string(std::string&)>;

class TCPServer
{
public:
    TCPServer(uint16_t port, func_t callback):port_(port),callback_(callback)
    {}
    ~TCPServer(){}

    bool InitServer()
    {
        listen_sockfd_.Socket();
        listen_sockfd_.Bind(port_);
        listen_sockfd_.Listen();
        lg(Info,"servr init ...done");
        return true;
    }

    void start() 
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while(true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listen_sockfd_.Accept(&clientip, &clientport);
            if(sockfd < 0)
                continue;
            lg(Info, "accept a new link, sockfd : %d , clientip : %s, clientport : %d",sockfd, clientip.c_str(), clientport);
            // 提供服务
            if(fork() == 0)
            {
                listen_sockfd_.Close();
                std::string inbuffer_stream;
                //数据处理
                while(true)
                {
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        lg(Debug,"debug : %s", inbuffer_stream.c_str());

                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);
                            if (info.empty())
                                break;
                            lg(Debug, "debug, response:\n%s", info.c_str());
                            lg(Debug, "debug:\n%s", inbuffer_stream.c_str());
                            write(sockfd, info.c_str(), info.size());
                        }

                    }
                    else if(n == 0)
                        break;
                    else 
                        break;
                }
                
                exit(0);
            }
            close(sockfd);
        }
    }
private:
    Sock listen_sockfd_;
    uint16_t port_;
    func_t callback_;
};